<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <div class="title">光谷智慧交通</div>
        <div class="options">
          <div
            v-for="option in options"
            :class="{
              options_item: true,
              active: activeType === option.type,
            }"
            @click="setActiveType(option.type)"
          >
            {{ option.name }}
          </div>
          <div class="tools">
            <el-dropdown>
              <span class="el-dropdown-link">
                工具箱
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>测距</el-dropdown-item>
                  <el-dropdown-item>导出图片</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      <el-main>
        <div id="map"></div>
        <query-form ref="queryFormRef" />
      </el-main>
    </el-container>
    <!-- 侧边抽屉组件 -->
    <side-drawer
      v-model:visible="mapStore.drawerVisible"
      :title="mapStore.drawerTitle"
      width="400px"
      @close="handleDrawerClose"
      @confirm="handleDrawerConfirm"
    >
      <!-- 根据不同类型显示不同表单组件 -->
      <component
        :is="getCurrentFormComponent()"
        ref="formRef"
        :coordinates="mapStore.currentCoordinates"
      />
    </side-drawer>
  </div>
</template>
<script setup>
import {
  ref,
  onBeforeMount,
  onMounted,
  shallowRef,
  markRaw,
  onUnmounted,
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowDown } from '@element-plus/icons-vue'
import { useMapStore } from '../stores/MapStore'
import SideDrawer from './common/SideDrawer.vue'
import TrafficReportForm from './forms/TrafficReportForm.vue'
import NoticeForm from './forms/NoticeForm.vue'
import NoticeListView from './forms/NoticeListView.vue'
import QueryForm from './forms/QueryForm.vue'
//路由相关
const route = useRoute()
const router = useRouter()
const activeType = ref('')
const options = ref([])
// 表单引用
const formRef = ref(null)
//查询表单引用
const queryFormRef = ref(null)
//使用地图store
const mapStore = useMapStore()
//头部选项们
const AllOptions = [
  {
    role: ['normal', 'traffic', 'admin'],
    name: '实时路况',
    type: 'traffic_status',
  },
  {
    role: ['normal', 'traffic', 'admin'],
    name: '查看公告',
    type: 'look_notice',
  },
  {
    role: ['normal', 'traffic', 'admin'],
    name: '报告路况',
    type: 'report_traffic',
  },
  {
    role: ['traffic', 'admin'],
    name: '发布公告',
    type: 'publish_notice',
  },
  {
    role: ['traffic', 'admin'],
    name: '事件查询',
    type: 'query_event',
  },
  {
    role: ['admin'],
    name: '用户管理',
    type: 'user_management',
  },
]
// 添加一个变量存储当前打开的popup
const currentPopup = ref(null)
// 根据抽屉类型获取对应的表单组件
const getCurrentFormComponent = () => {
  switch (mapStore.currentDrawerType) {
    case 'trafficReport':
      return markRaw(TrafficReportForm)
    case 'publishNotice':
      return markRaw(NoticeForm)
    case 'lookNotice':
      return markRaw(NoticeListView)
    default:
      return null
  }
}

// 抽屉关闭处理
const handleDrawerClose = () => {
  // 可以在这里执行清理工作
  console.log('抽屉关闭')
  // 禁用地图点击
  mapStore.disableMapClick()
  // 清除所有交互，包括画笔
  mapStore.clearInteractions()
  // 重置活动选项
  resetActive()
}

// 抽屉确认处理
const handleDrawerConfirm = async () => {
  if (!formRef.value) return
  try {
    // 根据抽屉类型处理不同表单的提交
    switch (mapStore.currentDrawerType) {
      case 'trafficReport':
        const formValues = await formRef.value.submitForm()
        if (formValues) {
          const result = await mapStore.saveTrafficReport(formValues)
          if (result) {
            // 提交成功后，重置表单并禁用地图点击
            formRef.value.resetForm()
            mapStore.disableMapClick()
            // 重置活动选项
            resetActive()
          }
        }
        break
      case 'publishNotice':
        const noticeData = await formRef.value.submitForm()
        if (noticeData) {
          // 发布成功后，关闭抽屉
          mapStore.drawerVisible = false
          // 重置活动选项
          resetActive()
        }
        break
      case 'lookNotice':
        // 查看公告不需要提交表单，直接关闭抽屉
        mapStore.drawerVisible = false
        // 重置活动选项
        resetActive()
        break
    }
  } catch (error) {
    console.error('表单提交错误:', error)
    ElMessage.error(error?.message || '表单提交失败')
  }
}

//头部选项选中样式
const setActiveType = (type) => {
  // 清除所有交互，包括画笔
  mapStore.clearInteractions()

  // 禁用之前可能的地图点击
  mapStore.disableMapClick()

  // 如果是实时路况，特殊处理：切换图层显示/隐藏，不影响选中状态
  if (type === 'traffic_status') {
    // 切换路况图层，返回值表示当前是否显示
    const isVisible = mapStore.toggleRoadLayer()
    // 根据图层显示状态设置选中状态
    activeType.value = isVisible ? 'traffic_status' : ''
    return
  }

  // 其他功能按正常逻辑处理
  // 如果当前项已经是激活状态，则取消选中
  if (activeType.value === type) {
    activeType.value = ''
    return
  }

  activeType.value = type
  switch (type) {
    case 'report_traffic':
      mapStore.reportTraffic()
      break
    case 'publish_notice':
      // 打开发布公告抽屉
      mapStore.drawerTitle = '发布公告'
      mapStore.currentDrawerType = 'publishNotice'
      mapStore.drawerVisible = true
      break
    case 'look_notice':
      // 打开查看公告抽屉
      mapStore.drawerTitle = '查看公告'
      mapStore.currentDrawerType = 'lookNotice'
      mapStore.drawerVisible = true
      break
    case 'query_event':
      // 处理拉框查询
      handleQueryEvent()
      break
  }
}

// 重置活动选项
const resetActive = () => {
  // 保存当前路况图层状态
  const roadLayerVisible = mapStore.getRoadLayerVisible()
  // 重置活动选项
  activeType.value = roadLayerVisible ? 'traffic_status' : ''
  // 清除交互和地图点击
  mapStore.clearInteractions()
  mapStore.disableMapClick()
}

// 处理事件查询
const handleQueryEvent = async () => {
  try {
    // 调用拉框查询，获取结果
    const queryResult = await mapStore.queryEvent()

    // 不管是否找到结果，都重置活动选项
    resetActive()

    // 如果有查询结果
    if (
      queryResult &&
      queryResult.features &&
      queryResult.features.length > 0
    ) {
      // 获取事件数据
      const eventData = mapStore.getQueryEventData(queryResult.features)

      // 计算表单显示位置，避免遮挡选区
      const position = { x: 0, y: 0 } // 使用固定位置对象替换mapStore.calculateFormPosition调用

      // 设置查询结果到表单并显示，同时传递原始features用于地图交互
      queryFormRef.value.setQueryResult(
        eventData,
        position,
        queryResult.features
      )
    } else {
      ElMessage.info('未找到事件数据')
    }
  } catch (error) {
    console.error('查询事件失败:', error)
    ElMessage.error('查询事件失败')
    // 发生错误时也重置活动选项
    resetActive()
  }
}

//挂载之前根据身份进行判断确定显示的选项
onBeforeMount(() => {
  const currentRole = route.fullPath.split('/')[1]
  console.log(currentRole)
  options.value = AllOptions.filter((i) => i.role.includes(currentRole))
})
onMounted(() => {
  //初始化地图
  mapStore.initMap('map')
  // 同步路况图层状态和选中状态
  if (mapStore.getRoadLayerVisible()) {
    activeType.value = 'traffic_status'
  }
  //测试
  //如果当前路由不包含normal(普通用户)，则给地图添加点击事件
  if (!route.fullPath.includes('normal')) {
    //给地图添加点击事件
    const map = mapStore.getMap()

    // 创建一个关闭popup的全局函数
    window.closeMonitorPopup = function () {
      if (currentPopup.value) {
        map.removeOverlay(currentPopup.value)
        currentPopup.value = null
      }
    }

    map.on('click', (event) => {
      let position = event.coordinate
      //定义一个查询成功的回调函数
      const querySuccess = (res) => {
        if (res.TotalCount > 0) {
          console.log('查询到的监控点', res)
          // 获取监控点信息
          const monitorNum = res.SFEleArray[0].AttValue[1]
          const monitorPosition = res.SFEleArray[0].AttValue[2]
          const monitorVideo = res.SFEleArray[0].AttValue[3]
          const monitorCoordinate = [
            res.SFEleArray[0].bound.xmax,
            res.SFEleArray[0].bound.ymax,
          ]

          // 如果已经有popup，先移除
          if (currentPopup.value) {
            map.removeOverlay(currentPopup.value)
          }

          // 在地图上添加自定义的popup展示监控点信息
          const popup = new ol.Overlay({
            element: document.createElement('div'),
            autoPan: false,
            autoPanMargin: 0,
            positioning: 'bottom-center',
          })

          // 设置popup内容，使用全局函数作为关闭按钮的onclick
          popup.element.innerHTML = `
            <div style="padding: 10px; background-color: white; border: 1px solid #ccc; border-radius: 4px;">
              <h4 style="display: flex; justify-content: space-between; align-items: center; margin-top: 0;">
                <span>${monitorNum}</span>
                <span onclick="window.closeMonitorPopup()" style="cursor: pointer; font-weight: bold; color: #666;">✕</span>
              </h4>
              <p>位置: ${monitorPosition}</p>
              <p>视频: ${monitorVideo}</p>
            </div>
          `

          // 存储当前popup以便后续关闭
          currentPopup.value = popup

          // 添加到地图
          map.addOverlay(popup)
          // 设置popup位置
          popup.setPosition(monitorCoordinate)
        }
      }
      mapStore.queryPointByPosition(position, querySuccess)
    })
  }
})
onUnmounted(() => {
  // 获取地图实例
  const map = mapStore.getMap()
  if (map) {
    // 移除所有点击事件监听器
    map.un('click')
  }
  // 清理全局函数
  window.closeMonitorPopup = null
})
</script>
<style scoped lang="scss">
.common-layout {
  .el-header {
    display: flex;
    align-items: center;
    .title {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin-right: 20px;
    }
    .options {
      display: flex;
      align-items: center;
      .options_item {
        padding: 20px;
        font-size: 16px;
        color: #909399;
        cursor: pointer;
        transition: background-color 0.3s, color 0.3s;
        &:hover {
          color: #303133;
        }
        &.active {
          color: #409eff;
        }
      }
      .tools {
        display: flex;
        align-items: center;
        padding: 20px;
        .el-dropdown-link {
          font-size: 16px;
          color: #909399;
          cursor: pointer;
          display: flex;
          align-items: center;
          &:focus,
          &:hover {
            outline: none;
            border: none;
          }
        }
      }
    }
  }
  .el-main {
    padding: 0;
    position: relative;
    height: calc(100vh - 60px);
    overflow: hidden;

    #map {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
    }
  }
}
</style>
